package com.seecen.cywbackend.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author : YJR
 * @className : FileUtil
 * @description : 使用阿里云OSS进行文件上传和管理
 * @createTime : 2023/6/24 19:14
 */
@Component
public class FileUtil {

    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    /**
     * 获取 OSS 客户端实例
     *
     * @return OSS 客户端
     */
    private OSS createOssClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上传文件并且获得永久URL
     *
     * @param inputStream 文件流
     * @param fileName    文件名称
     * @return 上传成功后返回的文件永久URL
     */
    public String uploadFileAndGetPermanentUrl(InputStream inputStream, String fileName) {
        // 确保文件名唯一，防止覆盖
        String uniqueFileName = UUID.randomUUID().toString() + "-" + fileName;
        OSS ossClient = null;
        try {
            // 创建 OSS 客户端
            ossClient = createOssClient();
            // 设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("application/octet-stream"); // 默认类型
            if (inputStream.available() > 0) {
                metadata.setContentLength(inputStream.available());
            }
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, inputStream, metadata);
            ossClient.putObject(putObjectRequest);
            // 设置对象为公共读取权限
            ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);
            // 构建永久访问URL
            String permanentUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
            return permanentUrl;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 确保关闭 OSS 客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
